<template>
	<a-card class="cardImp" :bordered="false" :loading="cardLoading">
		<a-tree
			v-if="localTreeData.length > 0"
			v-bind="$attrs"
			v-model:expandedKeys="expandedKeys"
			:field-names="treeFieldNames"
			:load-data="onLoadData"
			:tree-data="localTreeData"
		/>
		<a-empty v-else :image="Empty.PRESENTED_IMAGE_SIMPLE" />
	</a-card>
</template>

<script setup name="lazyTree">
	import { Empty } from 'ant-design-vue'

	const props = defineProps({
		//替换treeNode 中 children
		fieldNamesChildren: { type: String, default: 'children' },
		//替换treeNode 中 title
		fieldNamesTitle: { type: String, default: 'title' },
		//替换treeNode 中 key
		fieldNamesKey: { type: String, default: 'id' },
		//初始数据
		treeData: { type: Function, required: true },
		//父Id字段
		parentIdColumn: { type: String, default: 'parentId' },
		//默认顶级父Id值
		topValue: { default: 0 }
	})

	const cardLoading = ref(true) // 左侧树加载状态
	const expandedKeys = ref([]) // 默认展开的节点
	const selectedKeys = ref([]) // 选中的节点
	// 替换treeNode 中 title,key,children
	const treeFieldNames = { children: props.fieldNamesChildren, title: props.fieldNamesTitle, key: props.fieldNamesKey }
	const localTreeData = ref([])

	onMounted(() => {
		let parameter = {} //查询参数
		parameter[props.parentIdColumn] = props.topValue //默认从0开始
		loadTreeData(parameter) //获取数据
	})

	const loadTreeData = (parameter) => {
		const result = props.treeData(parameter) //调用父组件传递的方法
		if ((typeof result === 'object' || typeof result === 'function') && typeof result.then === 'function') {
			result.then((data) => {
				cardLoading.value = false
				if (data == null) {
					return
				}
				localTreeData.value = data
				//默认展开1级
				localTreeData.value.forEach((item) => {
					// 因为0的顶级
					if (item[props.parentIdColumn] == props.topValue) {
						expandedKeys.value.push(item[props.fieldNamesKey])
					}
					console.log(item)
					if (item[props.fieldNamesChildren].length == 0) {
						item.isLeaf = true
					}
				})
			})
		}
	}

	const onLoadData = (treeNode) => {
		return new Promise((resolve) => {
			// 判断是否已有子节点数据，有值了直接渲染
			if (treeNode[props.fieldNamesChildren].length > 0) {
				resolve()
				return
			}
			let parameter = {} //查询参数
			parameter[props.parentIdColumn] = treeNode[props.fieldNamesKey] //获取当前节点的id
			const result = props.treeData(parameter) //调用父组件传递的方法
			if ((typeof result === 'object' || typeof result === 'function') && typeof result.then === 'function') {
				result.then((data) => {
					setTimeout(() => {
						treeNode.dataRef[props.fieldNamesChildren] = data
						localTreeData.value = [...localTreeData.value]
						resolve()
					}, 500)
				})
			}
		})
	}
</script>

<style scoped>
	.cardImp {
		margin-right: 10px;
	}
</style>
